#!/bin/bash
# FigmaMCPWorkflow 执行脚本示例
# 用于自动化执行整个工作流

set -e  # 遇到错误立即停止

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 组件名称（从参数获取）
COMPONENT_NAME=$1
PARAMS_FILE=$2
OUTPUT_ROOT=${OUTPUT_ROOT:-"./${COMPONENT_NAME}"}
PHASE0_DIR="${OUTPUT_ROOT}/phase0"
PHASE1_DIR="${OUTPUT_ROOT}/phase1"
PHASE2_DIR="${OUTPUT_ROOT}/phase2"
PHASE3_DIR="${OUTPUT_ROOT}/phase3"
PHASE4_DIR="${OUTPUT_ROOT}/phase4"
PHASE5_DIR="${OUTPUT_ROOT}/phase5"

if [ -z "$COMPONENT_NAME" ]; then
  echo -e "${RED}错误: 请提供组件名称${NC}"
  echo "用法: $0 <ComponentName> [params.yaml]"
  exit 1
fi

if [ -z "$PARAMS_FILE" ]; then
  PARAMS_FILE="./params/${COMPONENT_NAME}.yaml"
fi

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  FigmaMCPWorkflow 自动执行脚本${NC}"
echo -e "${BLUE}  组件: ${COMPONENT_NAME}${NC}"
echo -e "${BLUE}  参数: ${PARAMS_FILE}${NC}"
echo -e "${BLUE}  输出目录: ${OUTPUT_ROOT}${NC}"
echo -e "${BLUE}========================================${NC}"

# Phase 0: 参数处理和方案解析
echo -e "\n${YELLOW}[Phase 0] 参数处理和方案解析...${NC}"
node scripts/phase0-validate.js "$PARAMS_FILE" "$OUTPUT_ROOT"
if [ $? -eq 0 ]; then
  echo -e "${GREEN}✓ Phase 0 完成${NC}"
  if [ -d "$PHASE0_DIR" ]; then
    ls -1 "$PHASE0_DIR"
  fi
else
  echo -e "${RED}✗ Phase 0 失败${NC}"
  exit 1
fi

# Phase 1: Figma数据提取
echo -e "\n${YELLOW}[Phase 1] Figma数据提取...${NC}"
node scripts/phase1-extract.js "$COMPONENT_NAME" "$OUTPUT_ROOT"
if [ $? -eq 0 ]; then
  echo -e "${GREEN}✓ Phase 1 完成${NC}"
  if [ -f "${PHASE1_DIR}/variables.json" ]; then
    echo "  - 设计变量: $(jq '.colors | length' ${PHASE1_DIR}/variables.json 2>/dev/null || echo '未知')"
  fi
  if [ -f "${PHASE1_DIR}/blueprint.json" ]; then
    echo "  - configurableProps: $(jq '.configurableProps | length' ${PHASE1_DIR}/blueprint.json)"
  fi
else
  echo -e "${RED}✗ Phase 1 失败${NC}"
  exit 1
fi

# Phase 2: Preview组件生成
echo -e "\n${YELLOW}[Phase 2] Preview组件生成...${NC}"
node scripts/phase2-generate.js "$COMPONENT_NAME" "$OUTPUT_ROOT"
if [ $? -eq 0 ]; then
  echo -e "${GREEN}✓ Phase 2 完成${NC}"
  # 编译检查
  echo "  检查TypeScript编译..."
  npx tsc --noEmit src/components/editor/schema/preview/components/${COMPONENT_NAME}/index.tsx
  if [ $? -eq 0 ]; then
    echo -e "  ${GREEN}✓ TypeScript编译通过${NC}"
  else
    echo -e "  ${RED}✗ TypeScript编译失败${NC}"
  fi
else
  echo -e "${RED}✗ Phase 2 失败${NC}"
  exit 1
fi

# Phase 3: 配置设计
echo -e "\n${YELLOW}[Phase 3] 配置设计...${NC}"
node scripts/phase3-config.js "$COMPONENT_NAME" "$OUTPUT_ROOT"
if [ $? -eq 0 ]; then
  echo -e "${GREEN}✓ Phase 3 完成${NC}"
  # 显示面板复用率
REUSE_RATE=$(node -e "
    const fs = require('fs');
    const file = '${PHASE3_DIR}/panel-reuse-analysis.json';
    if (fs.existsSync(file)) {
      const data = JSON.parse(fs.readFileSync(file, 'utf-8'));
      console.log(data.reuseRate || 0);
    } else {
      console.log(0);
    }
  ")
  echo "  - 面板复用率: ${REUSE_RATE}%"
  if (( $(echo "$REUSE_RATE > 85" | bc -l) )); then
    echo -e "  ${GREEN}✓ 复用率达标${NC}"
  else
    echo -e "  ${YELLOW}⚠ 复用率偏低${NC}"
  fi
else
  echo -e "${RED}✗ Phase 3 失败${NC}"
  exit 1
fi

# Phase 4: 配置面板渲染（条件执行）
echo -e "\n${YELLOW}[Phase 4] 配置面板渲染...${NC}"
NEEDS_CUSTOM_PANEL=$(node -e "
  const edit = require('./src/components/editor/schema/edit/aiComponents').${COMPONENT_NAME};
  const needsCustom = edit.some(p => p.includes('Custom') || p.includes('${COMPONENT_NAME}'));
  console.log(needsCustom ? 'true' : 'false');
")

if [ "$NEEDS_CUSTOM_PANEL" = "true" ]; then
node scripts/phase4-panel.js "$COMPONENT_NAME" "$OUTPUT_ROOT"
  if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Phase 4 完成${NC}"
  else
    echo -e "${RED}✗ Phase 4 失败${NC}"
    exit 1
  fi
else
  echo -e "${BLUE}⚡ Phase 4 跳过（无需自定义面板）${NC}"
fi

# Phase 5: 系统集成验证
echo -e "\n${YELLOW}[Phase 5] 系统集成验证...${NC}"
npm run phase5 -- "$COMPONENT_NAME"
if [ $? -eq 0 ]; then
  echo -e "${GREEN}✓ Phase 5 完成${NC}"
else
  echo -e "${RED}✗ Phase 5 失败${NC}"
  exit 1
fi

# ChainValidator（若 phase5 脚本未内置）
if npm run | grep -q "chain-validator"; then
  echo -e "\n${YELLOW}运行 ChainValidator...${NC}"
  npm run chain-validator -- "$COMPONENT_NAME"
fi

# 生成最终报告
echo -e "\n${BLUE}========================================${NC}"
echo -e "${BLUE}  工作流执行完成！${NC}"
echo -e "${BLUE}========================================${NC}"

# 显示验证报告摘要
if [ -f "${COMPONENT_NAME}/{PHASE5_DIR}/validation-results.json" ]; then
  echo -e "\n${YELLOW}验证报告摘要:${NC}"
  node -e "
    const report = require('${COMPONENT_NAME}/{PHASE5_DIR}/validation-results.json');
    console.log('  编译状态:', report.results?.compilation ? '✓' : '✗');
    console.log('  代码质量:', report.results?.linting ? '✓' : '✗');
    console.log('  三层架构:', report.results?.crossLayerConnectivity ? '✓' : '✗');
    console.log('  组件注册:', report.results?.registration ? '✓' : '✗');
    console.log('  ChainValidator 分数:', report.results?.chainValidator?.score ?? 'n/a');
    console.log('');
    console.log('  总体状态:', report.status || 'unknown');
  "
fi

# 输出下一步操作建议
echo -e "\n${YELLOW}下一步操作:${NC}"
echo "1. 启动开发服务器: npm run dev"
echo "2. 访问编辑器: http://localhost:3000/editor"
echo "3. 在左侧组件列表找到: ${COMPONENT_NAME}"
echo "4. 拖拽到画布进行测试，确认 Phase4/Phase5 产物全部生效"

# 询问是否启动开发服务器
echo -e "\n${YELLOW}是否立即启动开发服务器? (y/n)${NC}"
read -r response
if [[ "$response" =~ ^[Yy]$ ]]; then
  echo -e "${GREEN}启动开发服务器...${NC}"
  npm run dev
fi
